package com.icoolkj.ms.auth.controller;

import cn.hutool.core.util.IdUtil;
import com.icoolkj.ms.api.auth.dto.CaptchaDTO;
import com.icoolkj.ms.api.auth.vo.CaptchaVO;
import com.icoolkj.ms.auth.service.IAuthStrategy;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/20 17:38
 */
@Tag(name = "验证码")
@RequestMapping("/public/captcha")
@RestController
public class CaptchaController {

    /**
     * 生成图形验证码
     */
    @PostMapping("/getCode")
    @Operation(summary = "获取图形验证码", description = "用于登录时的图形验证码")
    public ServerResponseEntity<CaptchaVO> getCode(@Valid @RequestBody CaptchaDTO captchaDTO) {
        String grantType = captchaDTO.getGrantType();
        if (StringUtils.isBlank(grantType)) {
            return ServerResponseEntity.fail("授权类型不能为空!");
        }
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        return IAuthStrategy.getGenerateCaptcha("uuid", uuid);
    }

    /**
     * 生成短信验证码
     */
    @PostMapping("/getSmsCode")
    @Operation(summary = "获取短信验证码", description = "用于手机号登录的短信验证码")
    public ServerResponseEntity<CaptchaVO> getSmsCode(@Valid @RequestBody CaptchaDTO captchaDTO) {
        String grantType = captchaDTO.getGrantType();
        if (StringUtils.isBlank(grantType)) {
            return ServerResponseEntity.fail("授权类型不能为空!");
        }
        if (StringUtils.isBlank(captchaDTO.getPhoneNumber())) {
            return ServerResponseEntity.fail("手机号不能为空!");
        }
        // 先验证图形验证码
        boolean validateRes = IAuthStrategy.validateCodeByGrantType("uuid", captchaDTO);
        if (!validateRes) {
            return ServerResponseEntity.fail("图形验证码校验失败!");
        }
        return IAuthStrategy.getGenerateCaptcha("sms", captchaDTO.getPhoneNumber());
    }

    /**
     * 生成邮箱验证码
     */
    @PostMapping("/getEmailCode")
    @Operation(summary = "获取邮箱验证码", description = "用于邮箱登录的验证码")
    public ServerResponseEntity<CaptchaVO> getEmailCode(@Valid @RequestBody CaptchaDTO captchaDTO) {
        String grantType = captchaDTO.getGrantType();
        if (StringUtils.isBlank(grantType)) {
            return ServerResponseEntity.fail("授权类型不能为空!");
        }
        if (StringUtils.isBlank(captchaDTO.getEmail())) {
            return ServerResponseEntity.fail("邮箱不能为空!");
        }
        // 先验证图形验证码
        boolean validateRes = IAuthStrategy.validateCodeByGrantType("uuid", captchaDTO);
        if (!validateRes) {
            return ServerResponseEntity.fail("图形验证码校验失败!");
        }
        return IAuthStrategy.getGenerateCaptcha("email", captchaDTO.getEmail());
    }
}
